<template>
  <div class="template-detail-page">
    <!-- 页面头部 -->
    <div class="page-header">
      <div class="header-left">
        <el-button text @click="handleBack">
          <el-icon><ArrowLeft /></el-icon>
          返回
        </el-button>
        <h2>模板详情</h2>
        <el-tag v-if="applicationName" type="info" size="large">
          应用: {{ applicationName }}
        </el-tag>
      </div>
      <div class="header-right">
        <el-button type="primary" @click="handleEdit">
          <el-icon><Edit /></el-icon>
          编辑
        </el-button>
      </div>
    </div>

    <!-- 加载中 -->
    <div v-if="loading" class="loading-container">
      <el-skeleton :rows="10" animated />
    </div>

    <!-- 标签页切换 -->
    <el-tabs v-else v-model="activeTab" class="detail-tabs">
      <!-- Tab 1: 表单视图 -->
      <el-tab-pane label="表单视图" name="form">
        <template #label>
          <span class="tab-label">
            <el-icon><Document /></el-icon>
            表单视图
          </span>
        </template>
        <div class="tab-content">
          <TemplateFormRenderer
            v-model="formData"
            :fields-config="TEMPLATE_FIELDS_CONFIG"
            :readonly="true"
          />
        </div>
      </el-tab-pane>

      <!-- Tab 2: YAML 视图 -->
      <el-tab-pane label="YAML 视图" name="yaml">
        <template #label>
          <span class="tab-label">
            <el-icon><Notebook /></el-icon>
            YAML 视图
          </span>
        </template>
        <div class="tab-content yaml-view">
          <YamlEditor
            v-model="yamlContent"
            :readonly="true"
          />
        </div>
      </el-tab-pane>
    </el-tabs>
  </div>
</template>

<script setup>
import { ref, onMounted, computed } from 'vue';
import { useRoute, useRouter } from 'vue-router';
import { ElMessage } from 'element-plus';
import {
  ArrowLeft,
  Edit,
  Document,
  Notebook,
} from '@element-plus/icons-vue';
import TemplateFormRenderer from '@/components/TemplateFormRenderer/index.vue';
import YamlEditor from '@/components/YamlEditor/index.vue';
import { TEMPLATE_FIELDS_CONFIG } from '@/config/templateFieldsConfig';
import {
  parseYaml,
  extractFormData,
  deepClone,
} from '@/utils/yamlTemplateParser';
import { useTemplateStore } from '@/stores/template';
import { getApplications } from '@/api/configPreset';

const route = useRoute();
const router = useRouter();
const templateStore = useTemplateStore();

const activeTab = ref('form');
const loading = ref(true);
const template = ref(null);
const applicationName = ref('');

// 表单数据
const formData = ref({});
// YAML 字符串
const yamlContent = ref('');

const templateId = computed(() => route.params.id);

// 初始化
onMounted(async () => {
  await loadTemplate();
});

// 加载模板
async function loadTemplate() {
  loading.value = true;

  try {
    const data = await templateStore.getTemplateById(templateId.value);
    if (!data) {
      ElMessage.error('模板不存在');
      router.push('/experiment-templates');
      return;
    }

    template.value = data;

    // 解析 YAML
    const yamlData = parseYaml(data.yaml_content);

    // 提取表单数据
    formData.value = extractFormData(yamlData, TEMPLATE_FIELDS_CONFIG);

    // 设置 YAML 字符串
    yamlContent.value = data.yaml_content;

    // 加载应用名称
    if (data.application_id) {
      try {
        const appsRes = await getApplications({ active_only: false });
        const app = appsRes.items.find(a => a.id === data.application_id);
        if (app) {
          applicationName.value = app.name;
        }
      } catch (error) {
        console.error('加载应用名称失败:', error);
      }
    }
  } catch (error) {
    console.error('加载模板失败:', error);
    ElMessage.error('加载模板失败');
  } finally {
    loading.value = false;
  }
}

// 编辑
function handleEdit() {
  router.push(`/experiment-templates/${templateId.value}/edit`);
}

// 返回
function handleBack() {
  router.push('/experiment-templates');
}
</script>

<style scoped lang="scss">
.template-detail-page {
  height: 100%;
  display: flex;
  flex-direction: column;
  background-color: #f5f7fa;

  .page-header {
    display: flex;
    justify-content: space-between;
    align-items: center;
    padding: 16px 24px;
    background-color: #fff;
    border-bottom: 1px solid #e4e7ed;

    .header-left {
      display: flex;
      align-items: center;
      gap: 12px;

      h2 {
        margin: 0;
        font-size: 20px;
        font-weight: 600;
        color: #303133;
      }
    }

    .header-right {
      display: flex;
      gap: 12px;
    }
  }

  .loading-container {
    flex: 1;
    padding: 24px;
    background-color: #fff;
  }

  .detail-tabs {
    flex: 1;
    display: flex;
    flex-direction: column;
    background-color: #fff;
    margin: 0;

    :deep(.el-tabs__header) {
      margin: 0;
      padding: 0 24px;
      background-color: #fff;
      border-bottom: 1px solid #e4e7ed;
    }

    :deep(.el-tabs__content) {
      flex: 1;
      overflow: hidden;
    }

    :deep(.el-tab-pane) {
      height: 100%;
    }

    .tab-label {
      display: flex;
      align-items: center;
      gap: 6px;
      font-size: 14px;
    }

    .tab-content {
      height: 100%;
      overflow: auto;

      &.yaml-view {
        display: flex;
        flex-direction: column;
        padding: 0;
        overflow: hidden;

        :deep(.yaml-editor-wrapper) {
          flex: 1;
          overflow: hidden;
        }
      }
    }
  }
}
</style>
